package com.projectsexception.festivales.provider.handlers;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.projectsexception.festivales.provider.model.MapFestival;
import com.projectsexception.festivales.provider.util.SAXHandlerUtil;

public class MapsHandler extends DefaultHandler {
    
    private static final String MAP_ELEMENT = "map";
    private static final String NAME_ATTRIBUTE = "name";
    private static final String IMAGE_ELEMENT = "imageURL";
    
    private List<MapFestival> maps;
    
    private transient MapFestival tmpMap;
    private transient boolean mapURL;
    private transient StringBuilder sb;

    @Override
    public void startDocument() {
        maps = new ArrayList<MapFestival>();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        String s = SAXHandlerUtil.getElementName(localName, qName);
        if (s.equals(MAP_ELEMENT)) {
            tmpMap = new MapFestival();
            tmpMap.setName(attributes.getValue(NAME_ATTRIBUTE));
        } else if (s.equals(IMAGE_ELEMENT)) {
            mapURL = true;
            sb = new StringBuilder();
        }
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        if(mapURL) {
            sb.append(new String(ch,start,length));
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        String s = SAXHandlerUtil.getElementName(localName, qName);
        if (MAP_ELEMENT.equals(s)) {
            maps.add(tmpMap);
        } else if (s.equals(IMAGE_ELEMENT)) {
            mapURL = false;
            tmpMap.setImageURL(SAXHandlerUtil.cleanString(sb.toString()));
        }
    }

    public List<MapFestival> getResult() {
        return maps;
    }

}
